<html>
<head>
<script>
var childHosts = ["127.0.0.2", "127.0.0.3"];

var currentChild = 0;
var childFrame = null;
var done = false;

function getChildSrc() {
  return 'http://' + childHosts[currentChild] + ':8000/chrome_poc_child.html';
}

function print(msg) {
  let div = document.getElementById("div1");
  let text = div.innerHTML;
  text += msg + "<br />";
  div.innerHTML = text;
}

function resetChild() {
  if (done) return;
  print("resetChild");
  childFrame.src = getChildSrc();
  currentChild = (currentChild + 1) % childHosts.length;
  setTimeout(resetChild, 5000);
}

function createChildFrame() {
  let iframe = document.createElement('iframe');
  iframe.height = 1;
  iframe.width = 1;
  iframe.setAttribute('id', 'ifrm');
  iframe.src = getChildSrc();
  currentChild = (currentChild + 1) % childHosts.length;
  document.body.appendChild(iframe);
  childFrame = iframe;
}

function handleEvents(event) {
  if (event.data == "done") {
    done = true;
    print("done");
    event.source.postMessage("childDone", "*");
  }
}

window.addEventListener("message", handleEvents);

function main() {
  createChildFrame();
  setTimeout(resetChild, 5000);
}
</script>
</head>
<body onload="main()">
  <div id="div1"></div>
</body>
</html>
